import { createStore } from 'vuex';
import axios from 'axios';

const store = createStore({
  state: {
    user: {
      id: null,
      token: localStorage.getItem('userToken')// Assuming token is stored in localStorage
    },
    places: [] ,// 初始化为空数组，用于存储地点数据
    currentPlace: null ,// 新增加的当前编辑的地点对象
    placeId :null,
    tags :null,
    image :null,
  },
  mutations: {
    setUser(state, userData) {
      state.user.id = userData.id;
      state.user.token = userData.token;
      localStorage.setItem('userToken', userData.token); 
    },
    setPlaces(state,places) {
      state.places = places; // 存储从后端获取的所有地点数据
    },
    addPlace(state, place) {
      state.places.push(place); // 添加新地点到列表
    },
    removePlace(state, placeId) {
      state.places = state.places.filter(p => p.placeId !== placeId); // 删除指定ID的地点
    },
    updatePlace(state, updatedPlace) {
      const index = state.places.findIndex(p => p.placeId === updatedPlace.placeId);
      if (index !== -1) {
        state.places[index] = updatedPlace; // 直接更新数据确保响应性
      }
    },
    handleError(errorMessage) {
      console.error(errorMessage);
    }, 
  },
  actions:{
    async fetchPlaces({ commit, state }) {
      try {
        const response = await axios.get('/api/places/myplaces', {
          headers: { 'Authorization': state.user.token }
        });
        console.log("Data fetched:", response.data.data);
        commit('setPlaces', response.data.data);
      } catch (error) {
        console.error('Error fetching places:', error);
        commit('handleError', 'Failed to fetch places');
      }
    },
    async deletePlace({state }, placeId) {
    await axios.delete(`/api/places/delete`, {
          headers: { 'Authorization': state.user.token },
          params: { placeId }
        });
      } 
    },    
  async updatePlace({ commit, state }, updatedPlace) {
    try {
      const response = await axios.put('/api/places/update', updatedPlace, {
        headers: { 'Authorization': state.user.token }
      });
      if (response.data.code === 1) {
        commit('updatePlaceInState', updatedPlace);
      } else {
        commit('handleError', 'Failed to update place');
      }
    } catch (error) {
      console.error('Error updating place:', error);
      commit('handleError', 'Failed to update place');
    }
  },
  getters: {
    getPlaceById: (state) => (id) => {
      return state.places.find(place => place.placeId === id);
    }
  }
});


export default store;


